<!--
  * 工时功能
  *
  * @Author:    yjg
  * @Date:      2024-09-09 11:02:13
  * @Copyright  v1.0
-->
<template>
  <a-modal :title="form.workingHoursId ? '编辑' : '添加'" :width="600"  :open="visibleFlag"  @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" >
		<a-form-item label="加班日期" name="overtimeData">
		  <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="form.overtimeData" style="width: 100%" placeholder="加班日期" @change="handleOvertimeData"/>
		</a-form-item>
		<a-form-item label="部门" name="departmentIds">
		  <DepartmentTreeSelect ref="departmentTreeSelect" width="100%" :init="false" :disabled="form.workingHoursId != null || form.overtimeData == null" v-model:value="form.departmentIds" @change="handleDepartment"/>
		</a-form-item>
		<a-form-item label="人员选择" name="memberIdList">
		  <a-select mode="multiple" v-model:value="form.memberIdList" optionFilterProp="title" :disabled="form.workingHoursId != null" placeholder="请人员选择">
			<a-select-option v-for="item in memberList" :key="item.employeeId" :title="item.loginName">{{item.actualName}}{{item.loginName}}</a-select-option>
		  </a-select>
		</a-form-item>
		<a-form-item label="班别类型"  name="banbieType">
		  <DictSelect style="width: 100%" key-code="BANBIE_TYPE" v-model:value="form.banbieType" @change="handleChange()"/>
		</a-form-item>
		<a-form-item label="加班类型"  name="overtimeResult">
		  <DictSelect key-code="OVERTIM_TYPE" v-model:value="form.overtimeType" @change="handleChange()"/>
		</a-form-item>
		<a-form-item label="建议加班3" name="nightShiftOverTime">
		   <a-time-picker v-model:value="nightshiftStartOvertime" @change="shiftStartTime" format="HH:mm" :minute-step="30"/>
		   至
		   <a-time-picker v-model:value="nightshiftEndOvertime" @change="shiftEndTime"  format="HH:mm"  :minute-step="30"/>
		</a-form-item>
		<a-form-item label="加班数2"  name="overtimeNumber">
		  <a-input-number  style="width: 100%"  v-model:value="form.overtimeNumber2" placeholder="加班数2" />
		</a-form-item>
		 <a-form-item label="加班原因"  name="overtimeResult">
		   <a-textarea
		     :auto-size="{ minRows: 2, maxRows: 4 }"
		     v-model:value="form.overtimeResult"
		     placeholder="请输入加班原因"
		     :maxlength="250"
		     :showCount="true"
		   />
		 </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit()">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import { reactive, ref, nextTick } from 'vue';
  import dayjs, { Dayjs } from 'dayjs';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { workingHoursApi } from '/@/api/business/working-hours/working-hours-api';
  import { employeeApi } from '/@/api/system/employee-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { Solar } from 'lunar-javascript';
  import DepartmentTreeSelect from '/src/components/system/department-tree-select/multiple-choice.vue';
  
  const memberList = ref([]); //人员列表
  let solar = Solar.fromDate(new Date());
  let day = solar.toString();
  const overtimeData = ref();
  const nightshiftStartOvertime = ref(null);
  const nightshiftEndOvertime = ref(null);
 
  const nightShiftOverTime = ref<[Dayjs, Dayjs]>(); // 时间参数3
  
    // ------------------------ 时间范围 ------------------------
      const onNightshiftRangeChange = (value: [Dayjs, Dayjs], dateString: [string, string]) => {
     	form.nightshiftStartOvertime = dateString[0]
     	form.nightshiftEndOvertime = dateString[1]
      };
	  
	  const shiftStartTime = (value,dateString)=>{
	  		  form.nightshiftStartOvertime = dateString;
	  }
	  const shiftEndTime = (value,dateString)=>{
	  	  form.nightshiftEndOvertime = dateString;
	  }
	  
	  //-------------------------选择加班时间----------------------------
	  const handleOvertimeData = ()=>{
	  		  form.departmentIds = [];
	  }
	  
	  //---------------------------选择部门-------------------------------
	  const departmentTreeSelect = ref();
	  async function handleDepartment(){
	  	  try{
			//  form.memberIdList = [];
			  memberList.value = null;
			  if(form.departmentIds ==null || form.departmentIds.length === 0){
			  	return;
			  }  
	  		  let queryResult = await employeeApi.selectEmployeeByDeptIds(form.departmentIds,form.overtimeData,1)
			  memberList.value = queryResult.data
			 //  if(queryResult.data != null && queryResult.data.length > 0){
				// queryResult.data.forEach((item,index)=>{
				// 	form.memberIdList.push(item.employeeId)
				// })
			 //  }
	  	  }catch(e){
	  		  smartSentry.captureError(e);
	  	  } finally {
	          
	      }
	  }
	
	//---------------------------------班别类型------------------------------------
	
	const handleChange = () =>{
		nightshiftStartOvertime.value = null
		nightshiftEndOvertime.value =  null
		form.overtimeNumber2 = null
		form.nightshiftStartOvertime = null
		form.nightshiftEndOvertime = null
		if(form.banbieType == 'ZAOBAN' && form.overtimeType == 'DAILY_OVERTIME'){
			nightshiftStartOvertime.value = dayjs('18:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('20:00', 'HH:mm'); 
			form.overtimeNumber2 = 2
			form.nightshiftStartOvertime = '18:00'
			form.nightshiftEndOvertime = '20:00'
		}else if ((form.banbieType == 'BAIBAN' && form.overtimeType == 'WEEKEND_OVERTIME') || (form.banbieType == 'BAIBAN' && form.overtimeType == 'HOLIDAY_OVERTIME')){
			nightshiftStartOvertime.value = dayjs('08:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('20:00', 'HH:mm'); 
			form.overtimeNumber2 = 10
			form.nightshiftStartOvertime = '08:00'
			form.nightshiftEndOvertime = '20:00'
		}else if(form.banbieType == 'DAYEBAN' && form.overtimeType == 'DAILY_OVERTIME'){
			nightshiftStartOvertime.value = dayjs('06:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('08:00', 'HH:mm'); 
			form.overtimeNumber2 = 2
			form.nightshiftStartOvertime = '06:00'
			form.nightshiftEndOvertime = '08:00'
		}else if(form.banbieType == 'DAYEBAN' && form.overtimeType == 'WEEKEND_OVERTIME'){
			nightshiftStartOvertime.value = dayjs('20:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('08:00', 'HH:mm'); 
			form.overtimeNumber2 = 10
			form.nightshiftStartOvertime = '20:00'
			form.nightshiftEndOvertime = '08:00'
		}else if(form.banbieType == 'DAYEBAN' && form.overtimeType == 'HOLIDAY_OVERTIME'){
			nightshiftStartOvertime.value = dayjs('20:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('08:00', 'HH:mm'); 
			form.overtimeNumber2 = 10
			form.nightshiftStartOvertime = '20:00'
			form.nightshiftEndOvertime = '08:00'
		}
	}
	   function handleBanbieType(){
		   if(form.banbieType == 'ZAOBAN'){
			   form.overtimeType = 'DAILY_OVERTIME'
			   nightShiftOverTime.value = [ dayjs('18:00', "HH:mm"),  dayjs('20:00', "HH:mm")];
			   form.overtimeNumber2 = 2
			   form.nightshiftStartOvertime = '18:00'
			   form.nightshiftEndOvertime = '20:00'
			   
		   }else if(form.banbieType == 'BAIBAN'){
			   form.overtimeType = 'WEEKEND_OVERTIME'
			   nightShiftOverTime.value = [ dayjs('08:00', "HH:mm"),  dayjs('20:00', "HH:mm")];
			   form.overtimeNumber2 = 10
			   form.nightshiftStartOvertime = '08:00'
			   form.nightshiftEndOvertime = '20:00'
		   }else if(form.banbieType == 'DAYEBAN'){
			   form.overtimeType = null
			   nightShiftOverTime.value = [ dayjs('06:00', "HH:mm"),  dayjs('08:00', "HH:mm")];
			   form.overtimeNumber2 = 2
			   form.nightshiftStartOvertime = '06:00'
			   form.nightshiftEndOvertime = '08:00'
		   }else{
			   form.overtimeType = null
			   nightShiftOverTime.value = [ null, null];
			   form.overtimeNumber2 = null
			   form.nightshiftStartOvertime = null
			   form.nightshiftEndOvertime = null
		   }
	   }

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
	if(form.workingHoursId != null){
		nightShiftOverTime.value = [ dayjs(form.nightshiftStartOvertime, "HH:mm"),  dayjs(form.nightshiftEndOvertime, "HH:mm")];
	}else{
	   form.overtimeData = overtimeData.value
	}
	
	if (form.overtimeType && form.overtimeType.length > 0) {
	  form.overtimeType = form.overtimeType[0].valueCode;
	}
	if (form.banbieType && form.banbieType.length > 0) {
	  form.banbieType = form.banbieType[0].valueCode;
	}
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }
  

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
	  //工时ID
	  workingHoursId: undefined, 
	  //部门ID
	  departmentIds: undefined,
	  //部门名称
	  deptName: undefined, 
	  //姓名
	  name: undefined,
	  //工作号
	  jobNumber: undefined,
	  //班别类型
	  banbieType: undefined,
	  //加班日期
	  overtimeData : undefined,
	  //加班数2
	  overtimeNumber2: undefined,
	  //加班类型
	  overtimeType: undefined,
	  //建议加班开始时间3
	  nightshiftStartOvertime: undefined,
	  //建议加班结束时间3
	  nightshiftEndOvertime : undefined,
	  //加班原因
	  overtimeResult: undefined,
	  //人员信息
	  memberIdList: undefined,
	  //工时类型（0工时，1加班）
	  overtimeFlag: 1,
	  
  };
  
  let form = reactive(_.cloneDeep(formDefault));
  function reset() {
    Object.assign(form, formDefault);
    formRef.value.resetFields();
  }

  const rules = {
        departmentId: [{ required: true, message: '请选择部门' }],
		memberIdList: [{ required: true, message: '请选择人员' }],
		overtimeData: [{ required: true, message: '加班日期不能为空' }],
		banbieType: [{ required: true, message: '班别类型不能为空' }],
		overtimeType: [{ required: true, message: '加班类型不能为空' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
	  save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (form.workingHoursId) {
        await workingHoursApi.update(form);
      } else {
		console.log("form:",form)
		workingHoursApi.queryByNumberAndDate(form.jobNumber,form.overtimeData); //验证工号和日期
        await workingHoursApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
	  onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
